package com.smartodo.utils;

import java.util.List;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

import org.owasp.esapi.ESAPI;
import org.owasp.esapi.ValidationErrorList;
import com.smartodo.utils.Constants;;

/**
 * @author Pawan Singh
 * 
 */
public class WebUtils {

	/**
	 * Used to css/style an error message
	 */
	public static final String ERROR = "Error";

	/**
	 * Checks error hash to determine if a specific context is in error
	 * 
	 * @param errorHash
	 * @param key
	 * @return
	 */
	public static String getErrorStyle(String context) {
		
		ValidationErrorList errorList = getErrors();

		if (!errorList.isEmpty() && (errorList.getError(context) != null)) {
			return ERROR;
		}
		return "";
	}
	
	/**
	 * Hashed set of Error Messages
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static ValidationErrorList getErrors() {
			
		HttpServletRequest request = ESAPI.currentRequest();
		ValidationErrorList errors = new ValidationErrorList();
		
		if (request.getAttribute(Constants.ERROR_LIST) != null) {
			errors = (ValidationErrorList)request.getAttribute(Constants.ERROR_LIST);
		} 
		
		return errors;
	}
	
	/**
	 * reset all errors with list
	 * 
	 * @param newErrorList
	 */
	@SuppressWarnings("unchecked")
	public static void setErrors(ValidationErrorList newErrorList) {
			
		HttpServletRequest request = ESAPI.currentRequest();
		request.setAttribute(Constants.ERROR_LIST, newErrorList);
		
	}

	
	/**
	 * List "success" messages
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static List<String> getMessages() {
		
		HttpServletRequest request = ESAPI.currentRequest();
		
		ArrayList<String> messages = new ArrayList<String>();
		if (request.getAttribute(Constants.MESSAGE_LIST) != null) {
			messages = (ArrayList<String>)request.getAttribute(Constants.MESSAGE_LIST);
		} 
		
		return messages;
	}
	
	@SuppressWarnings("unchecked")
	public static void addMessage(String message) {
		HttpServletRequest request = ESAPI.httpUtilities().getCurrentRequest();
		
		ArrayList<String> messages = new ArrayList<String>();
		if (request.getAttribute(Constants.MESSAGE_LIST) != null) {
			messages = (ArrayList<String>)request.getAttribute(Constants.MESSAGE_LIST);
		} 
		
		messages.add(message);
		
		request.setAttribute(Constants.MESSAGE_LIST, messages);
	}

	
	/**
	 * 
	 * @param obj
	 * @return
	 */
	public static int makeInt(Object obj) {
		Integer returnMe = new Integer(obj.toString());
		return returnMe;
	}

	/**
	 * 
	 * @param obj
	 * @return
	 */
	public static String makeString(Object obj) {
		if (obj == null) return "";
		return obj.toString();
	}

}
